<template>
  <div class="indexContainer">
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
    />
    <el-form
      :rules="rules"
      ref="ruleForm"
      :model="formData"
      label-position="top"
    >
      <el-form-item required label="1、您对本次运输服务" prop="transport_score">
        <div class="rate">
          <el-rate
            v-model="formData.transport_score"
            :icon-classes="iconClasses"
            void-icon-class="icon-rate-face-off"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          >
          </el-rate>
          <div>
            {{
              formData.transport_score === 1
                ? "非常不满意"
                : formData.transport_score === 2
                ? "不满意"
                : formData.transport_score === 3
                ? "一般"
                : formData.transport_score === 4
                ? "满意"
                : formData.transport_score === 5
                ? "非常满意"
                : ""
            }}
          </div>
        </div>
      </el-form-item>
      <el-form-item required label="2、您对本次运输速度" prop="speed_score">
        <div class="rate">
          <el-rate
            v-model="formData.speed_score"
            :icon-classes="iconClasses"
            void-icon-class="icon-rate-face-off"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          >
          </el-rate>
          <div>
            {{
              formData.speed_score === 1
                ? "非常不满意"
                : formData.speed_score === 2
                ? "不满意"
                : formData.speed_score === 3
                ? "一般"
                : formData.speed_score === 4
                ? "满意"
                : formData.speed_score === 5
                ? "非常满意"
                : ""
            }}
          </div>
        </div>
      </el-form-item>
      <el-form-item
        required
        label="3、您对本次货物包装"
        prop="goods_package_score"
      >
        <div class="rate">
          <el-rate
            v-model="formData.goods_package_score"
            :icon-classes="iconClasses"
            void-icon-class="icon-rate-face-off"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          >
          </el-rate>
          <div>
            {{
              formData.goods_package_score === 1
                ? "非常不满意"
                : formData.goods_package_score === 2
                ? "不满意"
                : formData.goods_package_score === 3
                ? "一般"
                : formData.goods_package_score === 4
                ? "满意"
                : formData.goods_package_score === 5
                ? "非常满意"
                : ""
            }}
          </div>
        </div>
      </el-form-item>
      <div class="orderArea" @click="toOrderList">
        <div class="emptyWrap">
          <div v-if="orderNoStr">订单号： {{ orderNoStr }}</div>
          <div v-else>您可以选择具体订单，便于我们定位问题</div>
          <div style="width: 100%; text-align: end">选择订单 ></div>
        </div>
      </div>
      <el-form-item prop="order_ids"></el-form-item>
      <el-form-item
        label="4、说说您的具体感受？帮助我们为您和其他客户提供更好的服务"
        prop="propose"
        :required="proposeRequired"
      >
        <el-input
          type="textarea"
          placeholder="请填写您的问题描述"
          :rows="4"
          v-model="formData.propose"
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item v-if="isIOS">
        <el-upload
          action
          :auto-upload="false"
          :before-remove="beforeRemove"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-change="handleChange"
          :on-error="handleError"
          :file-list="fileList"
        >
          <div
            style="
              border: 1px solid #f5f6f7;
              padding: 30px 30px;
              background-color: #f5f6f7;
            "
          >
            <i class="el-icon-plus"></i>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="onSubmit" style="width: 100%"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import signString from "@/utils/sign";
import { uploading } from "../../page/material/common/common";
import { reqSubmitRate } from "@/api/rate";
export default {
  name: "rateIndex",
  data() {
    var validatePass = (rule, value, callback) => {
      if (this.proposeRequired && value === "") {
        callback(new Error("请填写您的问题描述"));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (this.proposeRequired && value.length === 0) {
        callback(new Error("请选择具体订单"));
      } else {
        callback();
      }
    };
    return {
      isWriting: true, //正在填写
      sender_id: "", //查订单用
      orderDetail: [],
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      iconClasses: ["icon-rate-face-1", "icon-rate-face-2", "icon-rate-face-3"], // 等同于 { 2: 'icon-rate-face-1', 4: { value: 'icon-rate-face-2', excluded: true }, 5: 'icon-rate-face-3' }
      formData: {
        order_ids: [],
        propose: "",
        transport_score: 0,
        speed_score: 0,
        goods_package_score: 0,
        urls: [],
        customer_id: "",
      },
      rules: {
        transport_score: {
          type: "number",
          min: 1,
          required: true,
          message: "请进行评价",
          trigger: ["blur", "change"],
        },
        speed_score: {
          type: "number",
          min: 1,
          required: true,
          message: "请进行评价",
          trigger: ["blur", "change"],
        },
        goods_package_score: {
          type: "number",
          min: 1,
          required: true,
          message: "请进行评价",
          trigger: ["blur", "change"],
        },
        propose: [{ validator: validatePass, trigger: "blur" }],
        order_ids: [{ validator: validatePass2, trigger: "blur" }],
      },
    };
  },
  computed: {
    proposeRequired() {
      if (
        this.formData.transport_score !== 0 &&
        this.formData.speed_score !== 0 &&
        this.formData.goods_package_score !== 0
      ) {
        return (
          this.formData.transport_score <= 2 ||
          this.formData.speed_score <= 2 ||
          this.formData.goods_package_score <= 2
        );
      } else {
        return false;
      }
    },
    orderNoStr() {
      let arr = this.orderDetail.map((item) => item.order_no);
      return arr.join("，");
    },
    isIOS() {
      //不是苹果系统就隐藏上传文件
      const userAgent = window.navigator.userAgent.toLowerCase();
      return /iphone|ipad|ipod|mac/.test(userAgent);
    },
  },
  watch: {
    $route: {
      handler() {
        this.$nextTick(() => {
          if (localStorage.getItem("serve_rate")) {
            this.formData = JSON.parse(localStorage.getItem("serve_rate"));
            this.fileList = this.formData.urls;
          }
          this.formData.customer_id = this.$route.query.customer_id || "";
          this.sender_id = this.$route.query.sender_id || "";
          this.orderDetail =
            this.$route.params.orderDetail ||
            JSON.parse(localStorage.getItem("orderDetail")) ||
            [];
          // this.formData.transport_score = this.$route.params.transport_score;
          // this.formData.goods_package_score =
          //   this.$route.params.goods_package_score;
          // this.formData.speed_score = this.$route.params.speed_score;
          this.formData.order_ids = this.orderDetail.map((item) => item.id);
        });
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    let that = this;
    window.addEventListener("beforeunload", () => {
      localStorage.removeItem("serve_rate");
      localStorage.removeItem("orderDetail");
    });
    // document.addEventListener("visibilitychange", function () {
    //   // 用户息屏、或者切到后台运行 （离开页面）
    //   if (document.visibilityState === "hidden") {
    //     localStorage.setItem("serve_rate", JSON.stringify(that.formData));
    //     localStorage.setItem("orderDetail", JSON.stringify(that.orderDetail));
    //   }
    // });

    // 用户打开或回到页面
    // if (document.visibilityState === "visible") {
    //   // console.log(document.visibilityState, "visible");
    //   if (localStorage.getItem("serve_rate")) {
    //     that.formData = JSON.parse(localStorage.getItem("serve_rate"));
    //     that.orderDetail =JSON.parse(localStorage.getItem("orderDetail"))

    //     that.fileList = that.formData.urls;
    //   }
    // }
  },
  methods: {
    // 上传的功能
    beforeRemove() {
      return this.$confirm("是否删除该图片");
    },
    handlePreview(file) {
      let piece = this.formData.urls.find((item) => item.name === file.name);
      this.dialogImageUrl = piece.url;
      this.dialogVisible = true;
    },
    handleRemove(file) {
      // console.log(file, "file");
      const index = this.formData.urls.findIndex(
        (item) => item.name === file.name
      );
      index > -1 && this.formData.urls.splice(index, 1);
    },
    handleChange(file, fileList, type) {
      this.fileList = fileList;
      var filelist = file.raw; //文件
      var filename = file.raw.uid + file.raw.name; //通过 uid和name组成文件的名字
      uploading(filelist, filename, type).then((res) => {
        this.formData.urls.push({
          name: file.name,
          url: res.res.requestUrls[0],
        });
        localStorage.setItem("serve_rate", JSON.stringify(this.formData));
        localStorage.setItem("orderDetail", JSON.stringify(this.orderDetail));

        // alert(res.res.requestUrls[0], "文件地址");
      });
    },
    handleError(err) {
      alert(err, "Error");
    },
    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let transport_score = this.formData.transport_score + "";
          let goods_package_score = this.formData.goods_package_score + "";
          let speed_score = this.formData.speed_score + "";
          let order_ids = JSON.stringify(this.formData.order_ids);
          let urls = JSON.stringify(this.formData.urls.map((item) => item.url));
          let timestamp = (new Date().getTime() + "").slice(0, 10);

          let sign = signString({
            ...this.formData,
            transport_score,
            goods_package_score,
            speed_score,
            sender_id: this.sender_id,
            timestamp,
            order_ids,
            urls,
          });
          let result = await reqSubmitRate({
            app_key: "9dae4a75d1b695b7c47ff0b36d3656d7",
            sign: sign,
            ...this.formData,
            transport_score,
            goods_package_score,
            speed_score,
            sender_id: this.sender_id,
            timestamp,
            order_ids,
            urls,
          });
          if (result.code === 10000) {
            localStorage.removeItem("serve_rate");
            localStorage.removeItem("orderDetail");

            this.$router.replace({
              path: "/resultPage",
            });
          }
        } else {
          return false;
        }
      });
    },
    toOrderList() {
      localStorage.setItem("serve_rate", JSON.stringify(this.formData));
      localStorage.setItem("orderDetail", JSON.stringify(this.orderDetail));

      // let orderIds = this.orderDetail.map((item) => item.id);
      let sender_id = this.sender_id;
      let customer_id = this.formData.customer_id;
      this.$router.push({
        path: "/orderList",
        query: {
          customer_id,
          sender_id,
        },
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
::v-deep .el-button {
  padding: 10px 15px !important;
  span {
    font-size: 16px;
  }
}

/deep/ .el-form-item__content {
  line-height: 0 !important;
}

/deep/ .el-rate__icon {
  font-size: 24px;
}

::v-deep .el-button {
  padding: 15px;
}

.indexContainer {
  padding: 20px;
  .rate {
    display: flex;
    align-items: center;
    div {
      margin: 0 20px;
      font-size: 16px;
    }
  }

  .orderArea {
    font-size: 14px;
    color: #606266;
    padding-bottom: 10px;
    .emptyWrap {
      border: 2px solid #fed296;
      border-radius: 5px;
      padding: 10px;
    }
  }
}
</style>
